{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Loops at English File level using Loop Files\n",
    "\n",
    "Before reading this notebook, we recommend that you first learn how to use placeholders in Qubiter,\n",
    "because placeholders and loops at the English file level are both used heavily in this notebook. They both go naturally together. Placeholder usage is illustrated in the notebook called `examples_of_placeholder_usage.ipynb` located in the same folder as this one.\n",
    "\n",
    "You can have loops at either the Python library level or the machine language level (i.e., English file). Both accomplish the same purpose. This notebook is only important to you if you want to use loops in an English file. The following talk explains some of the motivation and pros and cons of doing this. \n",
    "\n",
    "http://www.ar-tiste.com/jan2019QubiterPlaceholderAndLoops.pdf\n",
    " "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, change your working directory to the Qubiter directory in your computer and add its path to the path environment variable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/home/rrtucci/PycharmProjects/qubiter/qubiter/jupyter_notebooks\n",
      "/home/rrtucci/PycharmProjects/qubiter\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import sys\n",
    "print(os.getcwd())\n",
    "os.chdir('../../')\n",
    "print(os.getcwd())\n",
    "sys.path.insert(0,os.getcwd())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The next code writes English and Picture files for a circuit which contains \n",
    "2 nested loops and many placholder variables of \n",
    "either the hash followed by variable number type (e.g.,  `#9`)\n",
    "or the functional type (e.g., `-my_fun#1#2`)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loaded OneQubitGate, WITHOUT autograd.numpy\n"
     ]
    }
   ],
   "source": [
    "# some neccessary imports\n",
    "from qubiter.SEO_writer import *\n",
    "from qubiter.SEO_simulator import *\n",
    "from qubiter.StateVec import *\n",
    "from qubiter.LoopFileGenerator import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "file_prefix = 'loop_gen_test'\n",
    "num_qbits = 4\n",
    "\n",
    "# write the English and Picture files\n",
    "emb = CktEmbedder(num_qbits, num_qbits)\n",
    "wr = SEO_writer(file_prefix, emb)\n",
    "wr.write_controlled_one_qbit_gate(0,\n",
    "                                 Controls.new_single_trol(num_qbits, 2, False),\n",
    "                                 OneQubitGate.rot_ax,\n",
    "                                 ['#1', 1])\n",
    "wr.write_LOOP(20, nreps=2)\n",
    "wr.write_controlled_one_qbit_gate(1,\n",
    "                                 Controls.new_single_trol(num_qbits, 2, False),\n",
    "                                 OneQubitGate.rot_ax,\n",
    "                                 ['-my_fun1#1#2', 2])\n",
    "wr.write_LOOP(10, nreps=4)\n",
    "wr.write_controlled_one_qbit_gate(2,\n",
    "                                 Controls.new_single_trol(num_qbits, 3, True),\n",
    "                                 OneQubitGate.rot,\n",
    "                                 ['-#1*.5', '#2',  '-my_fun3#3'])\n",
    "wr.write_NEXT(10)\n",
    "wr.write_controlled_one_qbit_gate(1,\n",
    "                                 Controls.new_single_trol(num_qbits, 2, False),\n",
    "                                 OneQubitGate.rot_ax,\n",
    "                                 ['my_fun1#1#2', 2])\n",
    "wr.write_NEXT(20)\n",
    "wr.write_controlled_one_qbit_gate(0,\n",
    "                                 Controls.new_single_trol(num_qbits, 2, False),\n",
    "                                 OneQubitGate.rot_ax,\n",
    "                                 ['#1*.3', 1])\n",
    "wr.write_one_qbit_gate(1, OneQubitGate.rot_ax, ['my_fun#1', 1])\n",
    "wr.close_files()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The effect of the preceding code was to write the following English and Picture files\n",
    "\n",
    "* <a href=\"../io_folder/loop_gen_test_4_eng.txt\">../io_folder/loop_gen_test_4_eng.txt</a>\n",
    "* <a href=\"../io_folder/loop_gen_test_4_ZLpic.txt\">../io_folder/loop_gen_test_4_ZLpic.txt</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One can write a log file with info about the circuit just created simply by\n",
    "creating an object of the class SEO_reader with the flag `write_log` set to True."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<qubiter.SEO_reader.SEO_reader at 0x7f867854b150>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# write a log\n",
    "SEO_reader(file_prefix, num_qbits, write_log=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The preceding line of code created the following log file"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* <a href=\"../io_folder/loop_gen_test_4_log.txt\">../io_folder/loop_gen_test_4_log.txt</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The next code reads the English file just created and writes what we call a \"Loop File\". "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<qubiter.LoopFileGenerator.LoopFileGenerator at 0x7f864e49b050>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# write a Loop File\n",
    "LoopFileGenerator(file_prefix, num_qbits)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The preceding code created the following Loop File. \n",
    "\n",
    "* <a href=\"../io_folder/loop_gen_test_4_loop.py\">../io_folder/loop_gen_test_4_loop.py</a>\n",
    "\n",
    "Note that the line numbers given in the Loop file comments refer to lines in the English file. As you can see, a Loop file is a Python script\n",
    "with the same loop structure as the English file. You are supposed to\n",
    "copy the Loop file, give it a slightly different name, and modify it. We call the copy of the Loop file a \"Loop xfile\" (x for executable, because we intend to run it with exec()) The Loop xfile should have the same name as the Loop file \n",
    "except for a non-negative number that you insert between the word \"loop\" and the ending \".py\".\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next is a Loop xfile that we created from the above Loop file\n",
    "\n",
    "* <a href=\"../io_folder/loop_gen_test_4_loop1.py\">../io_folder/loop_gen_test_4_loop1.py</a>\n",
    "\n",
    "Note that the original Loop file has a line for each time a hash variable makes an appearance\n",
    "and for each time a function variable makes an appearance. The original Loop file\n",
    "gives a value of `None` to all appearances (uses) of each variable. You have\n",
    "a choice of replacing each None by a suitable value (in which case you are assigning it a new value) or leaving it as None. If you\n",
    "leave a variable as None, Qubiter will assume that you want it to take the value that was assigned to it the most recent time in its past that it was assigned a value different from None. This assumes that at the very least, the first time that the variable makes an appearance, its value is replaced from None to something else and suitable."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we create an object of the class SEO_simulator\n",
    "with the flag `xfile_number` equal to a non-negative number. The default value of that flag is -1, so any non-negative number tells the simulator object to execute a Loop xfile which ends with that xfile_num followed by \".py\". In our example, xfile_num=1\n",
    "\n",
    "Creating an object of SEO_simulator first executes the xfile and then\n",
    "runs through the circuit in the English file, duly jumping back to the matching LOOP line every time\n",
    "a NEXT is encountered, until the full number of repetitions (reps) has been performed.\n",
    "The report at the end of this notebook means that Qubiter succeeded in traversing through the circuit, using the info that it got from executing the xfile to correctly resolve the angle value of each gate.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "----------------------------------------\n",
      "*********branch= pure\n",
      "total probability of state vector (=one if no measurements)= 1.000000\n",
      "dictionary with key=qubit, value=(Prob(0), Prob(1))\n",
      "{0: (0.467015, 0.532985),\n",
      " 1: (0.417041, 0.582959),\n",
      " 2: (1.0, -0.0),\n",
      " 3: (1.0, -0.0)}\n"
     ]
    }
   ],
   "source": [
    "# read a Loop xfile and do simulation\n",
    "sim = SEO_simulator(file_prefix, num_qbits, verbose=False,\n",
    "                    xfile_num=1)\n",
    "print(\"\\n----------------------------------------\")\n",
    "StateVec.describe_st_vec_dict(sim.cur_st_vec_dict)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
